package io.xxx.xbutler.core.check;

import com.alibaba.fastjson2.JSONObject;
import io.xxx.xbutler.client.MaterialClient;
import io.xxx.xbutler.domain.Store;
import io.xxx.xbutler.domain.task.PushContext;
import io.xxx.xbutler.domain.task.Task;
import io.xxx.xbutler.domain.task.TaskItem;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Order(40)
@Component
public class MaterialChecker implements Checker {

    @Resource
    private MaterialClient materialClient;

    @Override
    public CheckError check(PushContext context) {
        Task task = context.getTask();
        Store store = context.getStore();
        List<TaskItem> taskItems = context.getTaskItems();
        Set<Long> notValidMaterialIds = new HashSet<>();
        for (TaskItem taskItem : taskItems) {
            JSONObject content = taskItem.getContent();
            Long materialId = content.getLong("materialId");
            if (materialId == null) {
                continue;
            }

            boolean validated = !notValidMaterialIds.contains(materialId) && materialClient.validateMaterial(materialId);
            if (!validated) {
                CheckError error = CheckError.MaterialNotValid;
                log.info("{}[taskId:{}, taskItemId:{}, storeId:{}, storeCode:{}, materialId:{}]", error.getErrorMessage(), task.getId(), taskItem.getId(), store.getId(), store.getCode(), materialId);
                notValidMaterialIds.add(materialId);
                taskItem.setError(error);
            }
        }
        return null;
    }

    @Override
    public boolean supports(PushContext context) {
        return context.getStore() != null;
    }
}
